package com.cy.duosearch.langchain.tool;

import dev.langchain4j.agent.tool.ToolExecutionRequest;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)  //
public class ToolUtil {

    public static ToolResult runTool(ToolExecutionRequest toolExecutionRequest) {

        String toolName = toolExecutionRequest.name();
        Class<?> aClass;
        try {
            // 先尝试直接加载类（可能是完整路径）
            aClass = Class.forName(toolName);
        } catch (ClassNotFoundException e) {
            // 获取当前类的包名，并与工具类名组合
            String packageName = ToolUtil.class.getPackage().getName();
            String fullClassName = packageName + "." + toolName;
            try {
                aClass = Class.forName(fullClassName);

            } catch (ClassNotFoundException ex) {
                System.err.println("工具加载失败: " + toolExecutionRequest.name());
                ex.printStackTrace();
                return ToolResult.error(ex.getMessage());
            }
        }

        Tool tool = (Tool) JsonUtil.jsonToObject(toolExecutionRequest.arguments(), aClass);
        return tool.runTool();
    }
}
